import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, getUserInfo as getUserInfoAPI, updateProfile, changePassword } from '@/api/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const loading = ref(false)

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 清除token
  const clearToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  // 登录
  const loginAction = async (loginData) => {
    try {
      loading.value = true
      const response = await login(loginData)
      const { access_token, user } = response.data
      
      setToken(access_token)
      userInfo.value = user
      
      ElMessage.success('登录成功')
      return response
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '登录失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const response = await getUserInfoAPI()
      userInfo.value = response.data.user
      return response
    } catch (error) {
      ElMessage.error('获取用户信息失败')
      throw error
    }
  }

  // 更新用户信息
  const updateProfileAction = async (profileData) => {
    try {
      loading.value = true
      const response = await updateProfile(profileData)
      userInfo.value = response.data.user
      ElMessage.success('更新成功')
      return response
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '更新失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePasswordAction = async (passwordData) => {
    try {
      loading.value = true
      const response = await changePassword(passwordData)
      ElMessage.success('密码修改成功')
      return response
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '密码修改失败')
      throw error
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = () => {
    clearToken()
    userInfo.value = null
    ElMessage.success('已退出登录')
  }

  return {
    token,
    userInfo,
    loading,
    setToken,
    clearToken,
    loginAction,
    getUserInfo,
    updateProfileAction,
    changePasswordAction,
    logout
  }
}) 